<template>
  <div class="todoapp">
    <TodoHander @createTask="onCreate" :arr="list" />
    <!-- 父向子传递数据 -->
    <TodoMain :arr="filterList" @delItem="onDelItem"/>
    <TodoFooter :arr="list" 
    @onClear="onClear" 
    :active="isActive"
    @setSelect="setSelect"/>
  </div>
</template>

<script>

import TodoHander from './components/TodoHander.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
export default {
  data () {
    return {
      // undone: 未完成  done: 已完成 all: 全部
      isActive: 'all',
      list:JSON.parse(localStorage.getItem('list')) || []
      // list: [
      //   { id: 100, name: "吃饭", isDone: true },
      //   { id: 201, name: "睡觉", isDone: false },
      //   { id: 103, name: "打豆豆", isDone: true },
      // ]
    }
  },

  watch:{
    list:{
      deep:true,
      handler(){
        localStorage.setItem('list',JSON.stringify(this.list))
      }
    }
  },

  components:{
    TodoHander,
    TodoMain,
    TodoFooter
  },

  created () {

  },

  methods: {
    // 添加数据
    onCreate(taskName){
      // 判断任务是否已经存在
      const flag = this.list.some(item => item.name===taskName)
      if(flag) return alert('任务已存在')
      const id = this.list.length ? this.list[this.list.length - 1].id + 1 : 100
      this.list.push({ 
        id, 
        name: taskName, 
        isDone: false })
    },
    // 清除已完成的数据
    onClear(undone){
      this.list = undone
    },
    // 选择状态：全部、未完成 、已完成
    setSelect(active){
      this.isActive = active
    },
    // 删除数据
    onDelItem(id){
      const index = this.list.findIndex(item => item.id === id)
      this.list.splice(index,1)
    }
  },
  computed:{
    filterList(){
      if(this.isActive === 'undone') return this.list.filter(item => !item.isDone);
      if(this.isActive === 'done') return this.list.filter(item => item.isDone);
      return this.list
    }
  }
}
</script>

<style scoped>

</style>
